package com.studorm.xml.action;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

import com.opensymphony.xwork2.ActionSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;

import com.studorm.Connection_mysql;
import com.studorm.XMLOption;
import com.studorm.vo.Repairs;



public class RepairsAction extends ActionSupport {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3697921271744988026L;
	// 此变量为存放你要读取的表格数据，前台请求后会自动生成JSON格式发送到客户端
	private List<Repairs> tableRow = new ArrayList<Repairs>();
	private int amountOfRow = 0;
	public List<Repairs> getTableRow() {
		return tableRow;
	}
	public void setTableRow(List<Repairs> tableRow) {
		this.tableRow = tableRow;
	}

	public String loadRepairs() throws Exception{
		//读取请求的参数 
		HttpServletRequest request = ServletActionContext.getRequest(); 
		String dormBdName = request.getParameter("dormBdName"); 
		String dormNu = request.getParameter("dormNu");
		String year = request.getParameter("year");
		String rowEachP_t = request.getParameter("rowEachP");//每页行数
		String nuOfP_t = request.getParameter("nuOfP");//要获取第几页的数据
		if(dormBdName == null || dormNu == null || year == null){
			return ERROR;
		}

		int rowEachP = 10; //每页行数
		int nuOfP = 1;//当前是第几页
		if(rowEachP_t != null){
			rowEachP = Integer.parseInt(rowEachP_t);
		}
		if(nuOfP_t != null){
			nuOfP = Integer.parseInt(nuOfP_t);
		}
		
		/* ---------------------------------------
		 * 		从dorminfs.xml 获取宿舍ID ver.12.18
		 * ---------------------------------------
		 * 
		 */
		String dorminfsPath=request.getSession().getServletContext().getRealPath("\\db\\xml\\dorminfs.xml");
		Document dorminfsDoc = XMLOption.loadXML(dorminfsPath);
		
		/*
		 * 读取选择的宿舍楼的所有宿舍id号
		 * 并合并成条件，用于读取整楼宿舍的
		 * 水电费的条件。如：
		 *  dorm=1 or dorm=3...
		 */
		StringBuilder dormidCondition = null;
		if(dormNu.equals("全部")){
			List<? extends Node> list = dorminfsDoc.selectNodes("/dorminfs/dorminf[dormBdName='"+dormBdName+"']");
			Iterator<? extends Node> it = list.iterator();
			dormidCondition = new StringBuilder();
			while(it.hasNext()){
				dormidCondition.append("dorm="+it.next().valueOf("@id"));
				if(it.hasNext()){
					dormidCondition.append(" or ");
				}
			}
		}else{
			List<? extends Node> list = dorminfsDoc.selectNodes("/dorminfs/dorminf[dormBdName='"+dormBdName+"' and dormNu='"+dormNu+"']");
			Iterator<? extends Node> it = list.iterator();
			dormidCondition = new StringBuilder();
			while(it.hasNext()){
				dormidCondition.append("dorm="+it.next().valueOf("@id"));
				if(it.hasNext()){
					dormidCondition.append(" or ");
				}
			}
		}

		String repairsPath=request.getSession().getServletContext().getRealPath("\\db\\xml\\repairs.xml");
		Document repairsDoc = XMLOption.loadXML(repairsPath);
		List<? extends Node> list = repairsDoc.selectNodes("/repairs/repair[("+dormidCondition.toString()+") and starts-with(submitDate,"+year+")]");
		amountOfRow = list.size();
		
		for(int count = (nuOfP-1) * rowEachP; count < (nuOfP-1) * rowEachP+rowEachP && count < list.size(); ++count){
			Node n = list.get(count);
			Repairs u = new Repairs();
			u.setDormBdName(dormBdName);
			
			// 在宿舍表里通过宿舍的id查询宿舍号
			Node dornNuNode = dorminfsDoc.selectSingleNode("dorminfs/dorminf[@id="+n.valueOf("dorm")+"]/dormNu");
			u.setDormNu(dornNuNode.getText());
			u.setId(Integer.parseInt(n.valueOf("@id")));
			u.setStudentNu(n.valueOf("studentNu"));
			u.setGoodsNu(n.valueOf("goodsNu"));
			u.setReasonOfRe(n.valueOf("reasonOfRe"));
			u.setSubmitDate(n.valueOf("submitDate"));
			u.setRepairsCost(Double.parseDouble(n.valueOf("repairsCost")));
			u.setIsrepairs(Integer.parseInt(n.valueOf("isrepairs")));	
			tableRow.add(u);
		}

		return SUCCESS;	
	}
	
	/* ---------------------------
	 * 		删除修理数据 ver.12.8
	 * ---------------------------
	 * 
	 * 从前台ajax请求获得delId参数
	 * 此参数为修理记录的ID，通过此ID
	 * 用SQL语句删除数据库中的记录
	 */
	public String delRepairs() throws Exception{
		//读取请求的参数 
				HttpServletRequest request = ServletActionContext.getRequest(); 
				String uId = request.getParameter("delId");

				if(uId == null){
					return NONE;
				}
				
				String repairsPath=request.getSession().getServletContext().getRealPath("\\db\\xml\\repairs.xml");
				Document repairsDoc = XMLOption.loadXML(repairsPath);
				Node delNode = repairsDoc.selectSingleNode("/repairs/repair[@id='"+uId+"']");
				if(delNode == null){
					return NONE;
				}
				Boolean succ = delNode.getParent().remove(delNode);
				
				if(succ){
					XMLOption.writeXml(repairsDoc, repairsPath);
					return SUCCESS;
				}else{
					return NONE;
				}
	}
	
	
	public int getAmountOfRow() {
		return amountOfRow;
	}
	public void setAmountOfRow(int amountOfRow) {
		this.amountOfRow = amountOfRow;
	}
	
	/* -----------------------------
	 * 	只读取一行指定水电费记录 ver.11.24
	 * -----------------------------
	 * 
	 */
	public String loadARepairs() throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest(); 
		String repId = request.getParameter("editId");
		Pattern patternNu = Pattern.compile("\\d*");
		if(repId == null || repId.isEmpty() || !patternNu.matcher(repId).matches()){
			return NONE;
		}
		String repairsPath=request.getSession().getServletContext().getRealPath("\\db\\xml\\repairs.xml");
		Document repairsDoc = XMLOption.loadXML(repairsPath);
		Node repairsNode = repairsDoc.selectSingleNode("/repairs/repair[@id='"+repId+"']");

		String dorminfsPath=request.getSession().getServletContext().getRealPath("\\db\\xml\\dorminfs.xml");
		Document dorminfsDoc = XMLOption.loadXML(dorminfsPath);
		Node dormNode = dorminfsDoc.selectSingleNode("/dorminfs/dorminf[@id='"+repairsNode.valueOf("dorm")+"']");

		Repairs u = new Repairs();

		u.setDormBdName(dormNode.valueOf("dormBdName"));
		u.setDormNu(dormNode.valueOf("dormNu"));
		u.setStudentNu(repairsNode.valueOf("studentNu"));
		u.setGoodsNu(repairsNode.valueOf("goodsNu"));
		u.setReasonOfRe(repairsNode.valueOf("reasonOfRe"));
		u.setSubmitDate(repairsNode.valueOf("submitDate"));
		u.setRepairsCost(Double.parseDouble(repairsNode.valueOf("repairsCost")));
		
		tableRow.add(u);		
	    return SUCCESS;
	}
	
	/* --------------------------------
	 * 		编辑水电费信息 ver.12.13
	 * --------------------------------
	 * 函数中的Pattern用来通过正则表达式验证输入
	 * 的字符串是否符合输入格式
	 * 
	 */
	public String editRepairs() throws Exception{
		
		Calendar rightNow = Calendar.getInstance();
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");//格式大小写有区别
		String submitDate = fmt.format(rightNow.getTime());
		
		HttpServletRequest request = ServletActionContext.getRequest(); 
	
		String studentNu = request.getParameter("studentNu");
		String goodsNu = request.getParameter("goodsNu");
		String reasonOfRe = request.getParameter("reasonOfRe");
		String repairsCost = request.getParameter("repairsCost");
		String id = request.getParameter("uid");
        
		Pattern patternNu = Pattern.compile("\\d*");
		Pattern patternDeci = Pattern.compile("\\d*\\.{0,1}\\d*"); // 匹配小数或整数
		
		if(id == null || id.isEmpty() || !patternNu.matcher(id).matches()){
			return NONE;
		}
		if(studentNu == null || id.isEmpty() || !patternNu.matcher(studentNu).matches()){
			return NONE;
		}
		if(goodsNu == null || id.isEmpty() || !patternNu.matcher(goodsNu).matches()){
			return NONE;
		}
	if(repairsCost == null || repairsCost.isEmpty() || !patternDeci.matcher(repairsCost).matches()){
			return NONE;
		}
	    
	String repairsPath=request.getSession().getServletContext().getRealPath("\\db\\xml\\repairs.xml");
	Document repairsDoc = XMLOption.loadXML(repairsPath);
	Node repairsNode = repairsDoc.selectSingleNode("/repairs/repair[@id='"+id+"']");
	
	
	(repairsNode.selectSingleNode("goodsNu")).setText(goodsNu);
    (repairsNode.selectSingleNode("reasonOfRe")).setText(reasonOfRe);
    (repairsNode.selectSingleNode("submitDate")).setText(submitDate);
    (repairsNode.selectSingleNode("repairsCost")).setText(repairsCost);
    XMLOption.writeXml(repairsDoc, repairsPath);
	
		return SUCCESS;
	
	}
	
	
	/* --------------------------------
	 * 		添加水电费信息 ver.11.23
	 * --------------------------------
	 * 函数中的Pattern用来通过正则表达式验证输入
	 * 的字符串是否符合输入格式
	 * 
	 */
	public String addRepairs() throws Exception{
		
		Calendar rightNow = Calendar.getInstance();
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");//格式大小写有区别
		String submitDate = fmt.format(rightNow.getTime());

		
		HttpServletRequest request = ServletActionContext.getRequest(); 
		String dormBdName = request.getParameter("dormBdName");
		String dormNu = request.getParameter("dormNu");
		String studentNu = request.getParameter("studentNu");
		String goodsNu = request.getParameter("goodsNu");
		String reasonOfRe = request.getParameter("reasonOfRe");
		String repairsCost = request.getParameter("repairsCost");

		Pattern patternNu = Pattern.compile("\\d{3}");// 匹配3位整数
		Pattern patternDeci = Pattern.compile("\\d*\\.{0,1}\\d*"); // 匹配小数或整数
		
		if(dormBdName.isEmpty() || dormBdName.equals("请选择")){
			return NONE;
		}
		if(dormNu == null || dormNu.isEmpty() || !patternNu.matcher(dormNu).matches()){
			return NONE;
		}
	
		if(studentNu == null ||studentNu.isEmpty()){
			return NONE;
		}
		if(goodsNu == null || goodsNu.isEmpty()){
			return NONE;
		}
		if(reasonOfRe == null || reasonOfRe.isEmpty()){
			return NONE;
		}
	if(repairsCost == null || repairsCost.isEmpty() || !patternDeci.matcher(repairsCost).matches()){
			return NONE;
		}
	
	
	
	
	// 获取宿舍ID
	String dorminfsPath=request.getSession().getServletContext().getRealPath("\\db\\xml\\dorminfs.xml");
	Document dorminfsDoc = XMLOption.loadXML(dorminfsPath);
	Node dormId = dorminfsDoc.selectSingleNode("/dorminfs/dorminf[dormBdName='"+dormBdName+"' and dormNu='"+dormNu+"']/@id");
	
	// 获取当前水电费ID递增数作为新水电费记录的ID，加1后保存以下次新增时使用
	String repairsPath=request.getSession().getServletContext().getRealPath("\\db\\xml\\repairs.xml");
	Document repairsDoc = XMLOption.loadXML(repairsPath);
	Node countNode = repairsDoc.selectSingleNode("/repairs/count");
	String count = countNode.getText();
	countNode.setText(String.valueOf(Integer.parseInt(count)+1));

	
	// 新增utility节点，设置属性id
	Element repairs = repairsDoc.getRootElement();
    Element repair=  repairs.addElement("repair");
	repair.addAttribute("id", count);
			
	// 新增dorm节点
			Element dorm = repair.addElement("dorm");
			dorm.setText(dormId.getText());
	      
			Element studentNuElement =repair.addElement("studentNu");
	        studentNuElement.setText(studentNu);
	        
	        Element goodsNuElement = repair.addElement("goodsNu");
	        goodsNuElement.setText(goodsNu);
	        
	        Element reasonOfReElement=repair.addElement("reasonOfRe");
	        reasonOfReElement.setText(reasonOfRe);
	        
	        Element submitDateElement = repair.addElement("submitDate");
	        submitDateElement.setText(submitDate);
	        
	        Element repairsCostElement = repair.addElement("repairsCost");
	        repairsCostElement.setText(repairsCost);
	        
	        Element isrepairsElement = repair.addElement("isrepairs");
	        isrepairsElement.setText("0");

	     // 保存
			XMLOption.writeXml(repairsDoc, repairsPath);
			

			return SUCCESS;

	}
	
	/* -----------------------------
	 * 		修改是否已维修 ver.12.16
	 * -----------------------------
	 * 
	 */
	public String alterisRepairs() throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest(); 
		String id = request.getParameter("alterId");
		String status = request.getParameter("status");
		Pattern patternNu = Pattern.compile("\\d*");
		if(id == null || id.isEmpty() || !patternNu.matcher(id).matches()){
			return NONE;
		}
		String repairsPath=request.getSession().getServletContext().getRealPath("\\db\\xml\\repairs.xml");
		Document repairsDoc = XMLOption.loadXML(repairsPath);
		Node ispayWNode = repairsDoc.selectSingleNode("/repairs/repair[@id='"+id+"']/isrepairs");
		
		if(status.equals("未维修")){
			ispayWNode.setText("1");
		}else if(status.equals("已维修")){
			ispayWNode.setText("0");
		}else{
			return NONE;
		}
		XMLOption.writeXml(repairsDoc, repairsPath);

		return SUCCESS;
	}
	public String loadStuRepairs() throws Exception
	{
		
		HttpServletRequest request = ServletActionContext.getRequest(); 
		HttpSession session = request.getSession();
		String id = (String)session.getAttribute("id");
		String sign = request.getParameter("issignin");	
	    int rowEachP = 10; //每页行数
		int nuOfP = 1;//当前是第几页
		
		
		int issign;
		
	
		
		if(id == null ||id.isEmpty()){		
			return NONE;
		}
		if(sign.equals("未维修"))
		{
			issign = 0;
		}
		else {
			issign=1;
		}
		//通过 studentsinfs.xml中的dorm值，查询出dorminfs中的宿舍及房号
		String studentsinfsPath=request.getSession().getServletContext().getRealPath("\\db\\xml\\studentsinfs.xml");
		Document studentsinfsDoc = XMLOption.loadXML(studentsinfsPath);
		Node studentsinfsNode = studentsinfsDoc.selectSingleNode("/studentsinfs/studentsinf[@studentNu='"+id+"']");

		String dorminfsPath=request.getSession().getServletContext().getRealPath("\\db\\xml\\dorminfs.xml");
		Document dorminfsDoc = XMLOption.loadXML(dorminfsPath);
		Node dormNode = dorminfsDoc.selectSingleNode("/dorminfs/dorminf[@id='"+studentsinfsNode.valueOf("dorm")+"']");
        //通过学号查询维修数据
		String repairsPath=request.getSession().getServletContext().getRealPath("\\db\\xml\\repairs.xml");
		Document repairsDoc = XMLOption.loadXML(repairsPath);
		List<? extends Node> list = repairsDoc.selectNodes("/repairs/repair[studentNu='"+id+"' and isrepairs='"+issign+"']");
		amountOfRow = list.size();
		
		for(int count = (nuOfP-1) * rowEachP; count < (nuOfP-1) * rowEachP+rowEachP && count < list.size(); ++count){
			Node n = list.get(count);
			Repairs u = new Repairs();
			u.setDormBdName(dormNode.valueOf("dormBdName"));
			
			// 在宿舍表里通过宿舍的id查询宿舍号
			u.setDormNu(dormNode.valueOf("dormNu"));
			u.setId(Integer.parseInt(n.valueOf("@id")));
			u.setStudentNu(n.valueOf("studentNu"));
			u.setGoodsNu(n.valueOf("goodsNu"));
			u.setReasonOfRe(n.valueOf("reasonOfRe"));
			u.setSubmitDate(n.valueOf("submitDate"));
			u.setRepairsCost(Double.parseDouble(n.valueOf("repairsCost")));
			u.setIsrepairs(Integer.parseInt(n.valueOf("isrepairs")));	
			tableRow.add(u);
		}
		
		
		
		
		
		
		
		
		
		
//		String sql = "SELECT  dormBdName, dormNu, studentNu, goodsNu, reasonOfRe, submitDate, repairsCost  FROM studormcms.reapairsmanage  WHERE studentNu = ? and isrepairs=?";
//		Connection conn = Connection_mysql.getConnection();
//		PreparedStatement ps = conn.prepareStatement(sql);
//		ps.setInt(1, Integer.parseInt(id));
//		ps.setInt(2,issign);
//		ResultSet res = ps.executeQuery();
//		while(res.next()){
//			Repairs u = new Repairs();
//			u.setDormBdName(res.getString("dormBdName"));
//			u.setDormNu(res.getString("dormNu"));
//			u.setStudentNu(res.getString("studentNu"));
//			u.setGoodsNu(res.getString("goodsNu"));
//			u.setReasonOfRe(res.getString("reasonOfRe"));
//			u.setSubmitDate(res.getString("submitDate"));
//			u.setRepairsCost(res.getDouble("repairsCost"));
//			tableRow.add(u);		
//		}
//		res.close();
//		ps.close();
//		conn.close();
		
		return SUCCESS;
	}
}
